<template>
  <!-- 工具栏 -->
  <div style="right: 40%;">
    <el-button-group id="toolbar">
      <el-tooltip
        class="item"
        effect="dark"
        content="放大"
        placement="bottom-start"
      >
        <el-button type="primary" @click="zoomIn">
          <svg-icon icon-class="zoomin" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="缩小"
        placement="bottom-start"
      >
        <el-button type="primary" @click="zoomOut">
          <svg-icon icon-class="zoomout" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="平移"
        placement="bottom-start"
      >
        <el-button type="primary" @click="panMap">
          <svg-icon icon-class="pan1" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="行政区划"
        placement="bottom-start"
      >
        <el-button type="primary" v-show="false">
          <svg-icon icon-class="xzqh" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="搜索"
        placement="bottom-start"
        v-if="false"
      >
        <el-button type="primary" @click="searchFeature">
          <svg-icon icon-class="search" />
        </el-button>
      </el-tooltip>
      <!-- <el-tooltip
        class="item"
        effect="dark"
        content="框选查询"
        placement="bottom-start"
        v-if="showquerybtn"
      >
        <el-button type="primary" @click="queryByExtent">
          <svg-icon icon-class="kuangxuan"
        /></el-button>
      </el-tooltip> -->
      <el-dropdown
        class="el-button el-button--medium"
        style="width: 56px; height: 36px; padding: 0px"
        @command="handleQueryCommand"
        v-if="false"
      >
        <el-button
          type="primary"
          style="
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
            margin-left: -1px;
            margin-top: -1px;
          "
        >
          <svg-icon icon-class="kuangxuan" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <!-- <el-dropdown-item command="point">点选查询</el-dropdown-item> -->
          <el-dropdown-item command="rectangle">框选查询</el-dropdown-item>
          <el-dropdown-item command="polygon">多边形查询</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-tooltip
        class="item"
        effect="dark"
        content="距离测量"
        placement="bottom-start"
      >
        <el-button size="medium" type="primary" @click="distanceMeasure">
          <svg-icon icon-class="distance" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="面积测量"
        placement="bottom-start"
      >
        <el-button size="medium" type="primary" @click="areaMeasure">
          <svg-icon icon-class="area" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="图层"
        placement="bottom-start"
      >
        <el-button size="medium" type="primary" @click="createLayerlist">
          <svg-icon icon-class="layers" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="图例"
        placement="bottom-start"
      >
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-tickets"
          @click="createLegend"
          v-if="false"
        ></el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="清除"
        placement="bottom-start"
      >
        <el-button type="primary" @click="clearGraphics">
          <svg-icon icon-class="clear" />
        </el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="查询面板"
        placement="bottom-start"
        v-if="false"
      >
        <el-button
          type="primary"
          icon="el-icon-s-order"
          @click="switchQueryPanel(!isShowQueryPanel)"
        ></el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="打印"
        placement="bottom-start"
        v-if="false"
      >
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-printer"
          @click="createPrint"
        ></el-button>
      </el-tooltip>
      <el-tooltip
        class="item"
        effect="dark"
        content="分析"
        placement="bottom-start"
        v-if="false"
      >
        <el-button
          size="medium"
          type="primary"
          icon="el-icon-discount"
          @click="createAnalysis"
        ></el-button>
      </el-tooltip>
    </el-button-group>
  </div>
</template>
<script>
import MapView from "@arcgis/core/views/MapView";
import Graphic from "@arcgis/core/Graphic";
import DistanceMeasurement2D from "@arcgis/core/widgets/DistanceMeasurement2D";
import AreaMeasurement2D from "@arcgis/core/widgets/AreaMeasurement2D";
import LayerList from "@arcgis/core/widgets/LayerList";
import Legend from "@arcgis/core/widgets/Legend";
import Print from "@arcgis/core/widgets/Print";
import ScaleBar from "@arcgis/core/widgets/ScaleBar";
import Zoom from "@arcgis/core/widgets/Zoom.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import SketchViewModel from "@arcgis/core/widgets/Sketch/SketchViewModel";
import Search from "@arcgis/core/widgets/Search";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import { createLayer } from "@/utils/map";
export default {
  // props: ['showquerybtn', 'mapview'],
  props: {
    showquerybtn: {
      type: Boolean,
      default: false,
    },
    mapview: { default: () => {} },
  },
  data() {
    return {
      // view: null,
      // webMap: null,
      currentWidget: null,
      dianzldHighlight: undefined,
      qitaldHighlight: null,
      roadldHighlight: null,
      featureLayer: undefined,
      isShowQueryPanel: false,
      highlight: undefined,
    };
  },
  computed: {
    // 这个页面使用这个好像不行，没找到原因
    // ...mapGetters("mapStore", [
    //   "roadFeatureLayer",
    //   "mianzldFeatureLayer",
    //   "gusmmFeatureLayer"
    // ]),
  },
  components: {},
  created() {},
  mounted() {},
  inject: [
    "sendQueryResults",
    "switchShowQueryPanel",
    "showResultDialog",
    "showDetailDialog",
  ],
  methods: {
    ...mapActions("map", ["setHighlight", "removeHighlight", "cleanHighlight"]),
    viewHandle: function (value) {
      console.log("调用viewHandel");
      this.mapview = value;
    },
    // 切换查询面板显示状态
    switchQueryPanel(isOpen) {
      if (isOpen) this.switchShowQueryPanel(true);
      else this.switchShowQueryPanel(false);
      this.isShowQueryPanel = isOpen;
      // this.$parent.switchShowQueryPanel(!this.isShowQueryPanel);
    },
    createAnalysis() {
      this.$emit("showComp", { flag: true });
    },
    removeWidget() {
      if (this.currentWidget) {
        this.mapview.ui.remove(this.currentWidget);
        this.currentWidget.destroy();
        if (
          this.currentWidget.id === "area" ||
          this.currentWidget.id === "distance"
        ) {
          console.log("removeMeasureWidget", this.currentWidget.id);
          this.$emit("measureWidgetRemoved");
        }

        this.currentWidget = null;
      }
    },
    // 搜索按钮
    searchFeature() {
      // 在地图上显示搜索面板
      let _self = this;
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "search") {
          this.removeWidget();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new Search({
        id: "search",
        view: _self.mapview,
        allPlaceholder: "请输入名称、标识码、养护单位名称",
        includeDefaultSources: false,
        locationEnabled: false,
        sources: [
          {
            layer: createLayer("dianzld"), // _self.$store.state.mapStore.roadFeatureLayer,
            searchFields: ["objcode", "objname", "yhmcname"],
            displayField: "objname",
            exactMatch: false,
            outFields: ["*"],
            name: "点状绿地",
            placeholder: "请输入",
          },
          {
            layer: createLayer("qitald"), //_self.$store.state.mapStore.qitaldFeatureLayer,
            searchFields: ["objcode", "objname", "yhmcname"],
            displayField: "objname",
            exactMatch: false,
            outFields: ["*"],
            name: "其他绿地",
            placeholder: "请输入",
          },
          {
            layer: createLayer("roadld"), //_self.$store.state.mapStore.roadldFeatureLayer,
            searchFields: ["objcode", "objname", "yhmcname"],
            displayField: "objname",
            exactMatch: false,
            outFields: ["*"],
            name: "道路附属绿地",
            placeholder: "请输入",
          },
          {
            layer: createLayer("gusmm"), //_self.$store.state.mapStore.gusmmFeatureLayer,
            searchFields: ["objcode", "objname", "yhmcname"],
            displayField: "objname",
            exactMatch: false,
            outFields: ["*"],
            name: "古树名木",
            placeholder: "请输入",
          },
        ],
      });
      _self.mapview.ui.add(_self.currentWidget, "top-left");
    },

    /**
     * @description: 空间查询
     * @param {*} command
     * @return {*}
     */
    handleQueryCommand(command) {
      switch (command) {
        case "point":
          this.queryByPoint();
          break;
        case "rectangle":
          this.queryByExtent();
          break;
        case "polygon":
          this.queryByPolygon();
          break;
        default:
          break;
      }
      // this.$message("click on item " + command);
    },

    /**
     * @description: 点选查询
     * @return {*}
     */
    queryByPoint() {
      let _self = this;
      _self.clearGraphics();
      if (_self.currentWidget) {
        if (_self.currentWidget.id != "point") {
          this.removeWidget();
        }
      }
      // 添加草绘微件
      const polygonSymbol = {
        type: "simple-fill",
        color: [227, 139, 79, 0.6],
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: "#722620",
          width: 3,
        },
      };
      const graphicsLayerSketch = new GraphicsLayer();
      _self.currentWidget = new SketchViewModel({
        id: "point",
        view: _self.mapview,
        layer: graphicsLayerSketch,
        polygonSymbol: polygonSymbol,
      });
      // drawing a polygon to select features on the map and table
      _self.currentWidget.on("create", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // _self.setQueryGeomery(event.graphic.geometry);
          _self.queryFeaturelayer(event.graphic.geometry);
          console.log(event.graphic);
          _self.mapview.goTo(event.graphic.geometry);
          _self.mapview.graphics.add(event.graphic);
          // 给父组件传值
          _self.$emit("extentChange", event.graphic.geometry);
        }
      });
      _self.currentWidget.create("point");
    },

    /**
     * @description: 框选查询（矩形查询）
     * @return {*}
     */
    queryByExtent() {
      let _self = this;
      _self.clearGraphics();
      if (_self.currentWidget) {
        if (_self.currentWidget.id != "rectangle") {
          this.removeWidget();
        }
      }
      // 添加草绘微件
      const polygonSymbol = {
        type: "simple-fill",
        color: [227, 139, 79, 0.6],
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: "#722620",
          width: 3,
        },
      };
      const graphicsLayerSketch = new GraphicsLayer();
      _self.currentWidget = new SketchViewModel({
        id: "rectangle",
        view: _self.mapview,
        layer: graphicsLayerSketch,
        polygonSymbol: polygonSymbol,
      });
      // drawing a rectangle to select features on the map and table
      _self.currentWidget.on("create", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // _self.setQueryGeomery(event.graphic.geometry);
          _self.queryFeaturelayer(event.graphic.geometry);
          _self.mapview.goTo(event.graphic.geometry);
          _self.mapview.graphics.add(event.graphic);
          // 给父组件传值
          _self.$emit("extentChange", event.graphic.geometry);
        }
      });
      //   _self.currentWidget.viewModel.newMeasurement();
      //   _self.currentWidget.viewModel.start();

      //   _self.mapview.ui.add(_self.currentWidget, "top-right");

      _self.currentWidget.create("rectangle");
    },
    /**
     * @description: 多边形查询
     * @return {*}
     */
    queryByPolygon() {
      let _self = this;
      _self.clearGraphics();
      if (_self.currentWidget) {
        if (_self.currentWidget.id != "polygon") {
          this.removeWidget();
        }
      }
      // 添加草绘微件
      const polygonSymbol = {
        type: "simple-fill",
        color: [227, 139, 79, 0.6],
        outline: {
          // autocasts as new SimpleLineSymbol()
          color: "#722620",
          width: 3,
        },
      };
      const graphicsLayerSketch = new GraphicsLayer();
      _self.currentWidget = new SketchViewModel({
        id: "polygon",
        view: _self.mapview,
        layer: graphicsLayerSketch,
        polygonSymbol: polygonSymbol,
      });
      // drawing a polygon to select features on the map and table
      _self.currentWidget.on("create", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          // _self.setQueryGeomery(event.graphic.geometry);
          _self.queryFeaturelayer(event.graphic.geometry);
          _self.mapview.goTo(event.graphic.geometry);
          _self.mapview.graphics.add(event.graphic);
          // 给父组件传值
          _self.$emit("extentChange", event.graphic.geometry);
        }
      });
      _self.currentWidget.create("polygon");
    },

    async queryFeaturelayer(geometry) {
      let _self = this;
      // 清除显示
      this.mapview.popup.close();
      this.mapview.graphics.removeAll();
      // 构建查询参数
      const spatialQueryParams = {
        spatialRelationship: "intersects", // 要应用的关系操作
        geometry: geometry, // 草绘要素几何
        // outFields: ["objcode", "objname"], // 要返回的属性
        outFields: ["objectid"], // 要返回的属性
        returnGeometry: true,
      };
      //****************************点状绿地查询****************************************//
      const roadFeatureLayer = createLayer("roadlayer");
      spatialQueryParams.start = undefined;
      spatialQueryParams.num = undefined;
      // 总数量
      // const dianzldFeaturesCount = await roadFeatureLayer.queryFeatureCount(
      //   spatialQueryParams
      // );
      // 查询全部数据，用于地图上高亮显示
      let dianzldFeatureSet = await roadFeatureLayer.queryFeatures(
        spatialQueryParams
      );
      let roadFeatureLayerView = _self.mapview.layerViews.filter(
        (view) => view.layer.title == "道路中心线"
      ).items[0];
      // roadFeatureLayerView = layerViews[0];
      console.log("roadFeatureLayerView", roadFeatureLayerView);
      _self.highlight = roadFeatureLayerView.highlight(
        dianzldFeatureSet.features
      );
      // 高亮显示
      // 设置符号和弹出窗口
      // dianzldFeatureSet.features.map((feature) => {
      //   feature.symbol =
      //     window.mapConfig.operationLayers.mapservers["dianzld"].symbol;
      //   // feature.popupTemplate = popupTemplate;
      //   return feature;
      // });

      // // 将要素添加至图形图层
      // this.mapview.graphics.addMany(dianzldFeatureSet.features);

      this.showResultDialog(geometry);
    },
    // 清除临时图形
    clearGraphics() {
      this.mapview.popup.close();
      this.highlight?.remove();
      this.mapview.graphics.removeAll();
      this.cleanHighlight();
      this.switchQueryPanel(false);
      this.removeWidget();
      // 给父组件传值
      this.$emit("clear");
    },
    //放大
    zoomIn() {
      let _self = this;
      // 如果微件不为空，判断是否是zoom，如果是就zoomin，否则删除微件，创建zoom，然后zoomin
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "zoom") {
          _self.currentWidget.zoomIn();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new Zoom({
        id: "zoomIn",
        view: this.mapview,
      });
      _self.currentWidget.zoomIn();
    },
    //缩小
    zoomOut() {
      let _self = this;
      // 如果微件不为空，判断是否是zoom，如果是就zoomin，否则删除微件，创建zoom，然后zoomin
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "zoom") {
          _self.currentWidget.zoomOut();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new Zoom({
        id: "zoom",
        view: this.mapview,
      });
      _self.currentWidget.zoomOut();
    },
    //平移地图
    panMap() {
      let _self = this;
      if (_self.currentWidget) this.removeWidget();
    },
    //二维距离测量
    distanceMeasure() {
      let _self = this;
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "distance") {
          this.removeWidget();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new DistanceMeasurement2D({
        id: "distance",
        view: _self.mapview,
      });
      _self.currentWidget.viewModel.start();
      //   _self.currentWidget.viewModel.newMeasurement();
      _self.$emit("measureWidgetAdded");
      _self.mapview.ui.add(_self.currentWidget, "top-right");
    },
    //二维面积测量
    areaMeasure() {
      let _self = this;
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "area") {
          this.removeWidget();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new AreaMeasurement2D({
        id: "area",
        view: _self.mapview,
      });
      //   _self.currentWidget.viewModel.newMeasurement();
      _self.currentWidget.viewModel.start();
      _self.$emit("measureWidgetAdded");
      _self.mapview.ui.add(_self.currentWidget, "top-right");
    },
    //二维图层列表
    createLayerlist() {
      let _self = this;
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "layerList") {
          this.removeWidget();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new LayerList({
        id: "layerList",
        view: _self.mapview,
        listItemCreatedFunction: (event) => {
          const item = event.item;
          console.log(item.layer.id);
          console.log(item.layer.title);
          console.log(item.layer.type);
          item.layer.title = item.layer.title;
          //   if (item.layer.type == 'tile')
          //     return;
          // if (item.layer.type != "group" && item.layer.type != "web-tile") {
          //   // don't show legend twice
          //   item.panel = {
          //     content: "legend",
          //     open: false,
          //   };
          // }
        },
      });
      //指示用户是否可以选择列表项。通过使用鼠标或触摸屏拖动手势，或者使用键盘上的箭头键，可以在列表中对所选项目进行重新排序。
      _self.currentWidget.selectionEnabled = true;
      _self.mapview.ui.add(_self.currentWidget, "top-right");
    },
    //二维图例
    createLegend() {
      let _self = this;
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "legend") {
          this.removeWidget();
          return;
        } else {
          this.removeWidget();
        }
      }
      let legend = null;
      if (_self.webMap == null) return;
      const featureLayer = _self.webMap.layers.getItemAt(0);
      _self.currentWidget = new Legend({
        id: "legend",
        view: _self.mapview,
      });
      _self.mapview.ui.add(_self.currentWidget, "bottom-left");
    },
    //二维打印
    createPrint() {
      let _self = this;
      if (_self.currentWidget) {
        if (_self.currentWidget.id == "print") {
          this.removeWidget();
          return;
        } else {
          this.removeWidget();
        }
      }
      _self.currentWidget = new Print({
        id: "print",
        view: _self.mapview,
        printServiceUrl:
          "https://utility.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task",
      });
      _self.mapview.ui.add(_self.currentWidget, "top-right");
    },
    //二维比例尺
    createScalebar() {
      let _self = this;
      _self.scalebar = new ScaleBar({
        view: _self.mapview,
        unit: "dual", // The scale bar displays both metric and non-metric units.
      });

      _self.mapview.ui.add(_self.scalebar, "bottom-left");
    },
  },

  mounted() {
    // this.$store.state.mapStore.mapView.ui.add("analysiscomp", "top-right");
  },
  // computed: {
  //   listenMapView() {
  //     return this.$store.state.mapStore.mapView;
  //   },
  // },
  // watch: {
  //   listenMapView(newVal, oldVal) {
  //     if (newVal) {
  //       this.view = this.$store.state.mapStore.mapView;
  //       this.webMap = this.$store.state.mapStore.webMap;
  //       // this.createScalebar();
  //       // this.view.ui.add("toprightDiv", "top-right");
  //     }
  //   },
  // },
};
</script>
<style lang="scss">
.btnclass {
  background-color: #fff !important;
}

.iconfont {
  width: 56px !important;
  height: 40px !important;
}

.analysisclass {
  width: 330px;
  height: 600px;
}

//修改icon
.el-icon-my-export {
  background: url("../../assets/icons/icon-point.png") no-repeat;
  font-size: 16px;
  background-size: cover;
  width: 15px;
  height: 15px;
}
</style>
